package javase.ch03.tongxun.lock;

import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;

public class House {
    private int count = 0;
    private final Lock lock = new ReentrantLock(); // 创建Lock对象

    // 存货方法
    public void store() {
        lock.lock(); // 获取锁
        try {
            count++;
            System.out.println(Thread.currentThread().getName() + " 存货，库存为: " + count);
        } finally {
            lock.unlock(); // 释放锁
        }
    }

    // 销售方法
    public void sale() {
        lock.lock(); // 获取锁
        try {
            if (count > 0) {
                count--;
                System.out.println(Thread.currentThread().getName() + " 销售，库存为: " + count);
            } else {
                System.out.println(Thread.currentThread().getName() + " 无货");
            }
        } finally {
            lock.unlock(); // 释放锁
        }
    }
}
